package com.atguigu.bigdata.chapter07.window;

import com.atguigu.bigdata.bean.WaterSensor;
import com.atguigu.bigdata.util.AtguiguUtil;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.List;

/**
 * @Author lzc
 * @Date 2022/9/4 8:28
 */
public class Flink03_Window_NoKey {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
    
        env
            .socketTextStream("hadoop162", 8888)
            .map(new MapFunction<String, WaterSensor>() {
                @Override
                public WaterSensor map(String value) throws Exception {
                    String[] data = value.split(",");
                    return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
                }
            })
            // 没有keyBy窗口, 要求所有的元素进入同一个窗口
            .windowAll(TumblingProcessingTimeWindows.of(Time.seconds(5)))
            // 所以要求窗口处理函数的并行度必须是1
            // select sum(..) from t;
            .process(new ProcessAllWindowFunction<WaterSensor, String, TimeWindow>() {
                @Override
                public void process(Context ctx,
                                    Iterable<WaterSensor> elements,
                                    Collector<String> out) throws Exception {
                    String stt = AtguiguUtil.toDatTime(ctx.window().getStart());
                    String edt = AtguiguUtil.toDatTime(ctx.window().getEnd());
    
                    List<WaterSensor> list = AtguiguUtil.toList(elements);
    
                    out.collect(stt + "  " + edt + " " + list);
                }
            })
            .print();
         
       
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*


 */